<?php

namespace app\common\model;

use think\Model;
use app\common\model\User;
use think\Exception;
use think\Db;
use EasyWeChat\Foundation\Application;
use addons\wechat\library\Config as ConfigService;

/**
 * 返利模型
 */
class Rebate Extends Model
{

    /**
     * [create_rebate 创建返利  普通用户购买和分销商购买 分销商店铺]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    [type]      $order_id [description]
     */
    public static function createRebate($order_id)
    {
        $order = Order::get($order_id);
          //店铺分销商
        $distributor = Db::name('distributor')->where(['user_id'=>$order['sell_id']])->find();
        $allocation  = Db::name('distribution_allocation')->where(['goods_id'=>$order['goods_id']])->find();
               
        //单独配置的直营分销商
        if ($distributor['direct']) {
                    $rebate = [
                            'store_id'       => $order['store_id'],
                            'order_id'       => $order['id'],
                            'distributor_id' => $distributor['user_id'],
                            'is_partner'     => 0,
                            'buy_role'       => $order['buy_role'],
                            'user_id'        => $order['user_id'],
                            'ticket_num'     => $order['ticket_num']
                     ]; 
                     if ($allocation['unified'] == 1) {
                         $distributor_goods = Db::name('distributor_goods')
                                             ->where(['user_id'=>$distributor['user_id'],'goods_id'=>$order['goods_id']])
                                             ->find();
                          $rebate['money']  = ($distributor_goods['market_price']*$order['ticket_num']);
                          $rebate_money = $rebate['money'];
                           if ($rebate['money'] > 0) {
                                self::insertDistributorRebate($rebate);
                            }
                     }else{
                          $rebate['money'] = ($allocation['three_price']*$order['ticket_num']);
                          $rebate_money = $rebate['money'];
                          if ($rebate['money'] > 0) {
                                self::insertDistributorRebate($rebate);
                         }
                     }
        }else{  
                    if ($allocation['unified'] == 1) {
                        $rebate = [
                            'store_id'       => $order['store_id'],
                            'order_id'       => $order['id'],
                            'distributor_id' => $distributor['user_id'],
                            'is_partner'     => 0,
                            'buy_role'       => $order['buy_role'],
                            'user_id'        => $order['user_id'],
                            'ticket_num'     => $order['ticket_num']
                        ]; 
                        $distributor_goods = Db::name('distributor_goods')
                                       ->where(['user_id'=>$distributor['id'],'goods_id'=>$order['goods_id']])
                                       ->find();
                        $rebate['money']  = ($distributor_goods['market_price']*$order['ticket_num']);
                        $rebate_money = $rebate['money'];
                        if ($rebate['money'] > 0) {
                            self::insertDistributorRebate($rebate);
                        }
                    }else{
                            //默认配置分销商
                            switch ($distributor['level']) {
                                 case '1':
                                   $market_money = $allocation['one_price']*$order['ticket_num'];
                                   break;
                                 case '2':
                                   $market_money = $allocation['two_price']*$order['ticket_num'];
                                   break;
                                 case '3':
                                   $market_money = $allocation['three_price']*$order['ticket_num'];
                                   break;  
                                 default:
                                   break;
                               }
                               $rebate = [
                                          'store_id'       => $order['store_id'],
                                          'order_id'       => $order['id'],
                                          'distributor_id' => $distributor['user_id'],
                                          'is_partner'     => 0,
                                          'buy_role'       => $order['buy_role'],
                                          'user_id'        => $order['user_id'],
                                          'ticket_num'     => $order['ticket_num'],
                                          'money'          => $market_money
                                ];

                                $rebate_money = $market_money;

                                if ($order['buy_role'] == 3) {
                                    //普通用户下单
                                    if ($market_money > 0) { 
                                     self::insertDistributorRebate($rebate);
                                    }
                                }else{
                                    //分销商下单
                                    if ($market_money > 0 && $allocation['floor_price'] == 1) {
                                        self::insertDistributorRebate($rebate);
                                    }elseif ($market_money > 0 && $allocation['floor_price'] == 2 && $distributor['floor_price'] == 0) {
                                        self::insertDistributorRebate($rebate);
                                    }else{
                                        $rebate_money = 0; 
                                    } 
                                }  
                               
                                //分销商推荐人
                               if ($distributor['parent_id'] > 0) {
                                 $parent = Db::name('distributor')->field('level,parent_id')->where(['user_id'=>$distributor['parent_id']])->find();
                                 switch ($parent['level']) {
                                   case '1':
                                     if ($distributor['level'] == 1) {
                                        $parent_money  = ($allocation['team_award']*$order['ticket_num'])*0.5;
                                     }else{
                                        $parent_money  = (($allocation['one_price']*$order['ticket_num'])-$market_money);
                                     }
                                     break;
                                    case '2':
                                     if ($distributor['level'] == 2) {
                                       $parent_money  = ($allocation['team_award']*$order['ticket_num'])*0.4;
                                     }else{
                                       $parent_money  = (($allocation['two_price']*$order['ticket_num'])-$market_money);
                                     }
                                     break;
                                   case '3':
                                        $parent_money = ($allocation['team_award']*$order['ticket_num'])*0.3;
                                     break;                                                                                         
                                   default:
                                     break;
                                 }
                                    $rebate_money+=$parent_money;
                                    if ($parent_money > 0) {
                                      $parent_rebate = [
                                              'store_id'       => $order['store_id'],
                                              'order_id'       => $order['id'],
                                              'distributor_id' => $distributor['parent_id'],
                                              'is_partner'     => 1,
                                              'buy_role'       => $order['buy_role'],
                                              'user_id'        => $order['user_id'],
                                              'ticket_num'     => $order['ticket_num'],
                                              'money'          => $parent_money
                                      ];    
                                     self::insertDistributorRebate($parent_rebate); 
                                    }
                                    //分销商推荐人的推荐人
                                    if ($parent['parent_id'] > 0) {
                                        $parent2 = Db::name('distributor')->field('level')->where(['user_id'=>$parent['parent_id']])->find();
                                        switch ($parent2['level']) {
                                            case '1':
                                                if ($parent['level'] == 1) {
                                                  $parent2_money  = ($allocation['team_award']*$order['ticket_num'])*0.4;
                                                }elseif ($parent['level'] == 2) {
                                                  $parent2_money  = (($allocation['one_price']-$allocation['two_price'])*$order['ticket_num']);
                                                }else{
                                                  $parent2_money  = (($allocation['one_price']-$allocation['three_price'])*$order['ticket_num']);
                                                }
                                            break;
                                            case '2':
                                                if ($parent['level'] == 2) {
                                                  $parent2_money  = ($allocation['team_award']*$order['ticket_num'])*0.3;
                                                }else{
                                                  $parent2_money  = (($allocation['two_price']*$order['ticket_num'])-$market_money);
                                                }
                                            break;
                                            case '3':
                                                  $parent2_money  = ($allocation['team_award']*$order['ticket_num'])*0.2;
                                             break;                                                                                                          
                                            default:
                                            break;
                                        }
                                        $rebate_money+=$parent2_money;
                                        if ($parent2_money > 0) {
                                            $parent2_rebate = [
                                                'store_id'       => $order['store_id'],
                                                'order_id'       => $order['id'],
                                                'distributor_id' => $parent['parent_id'],
                                                'is_partner'     => 1,
                                                'buy_role'       => $order['buy_role'],
                                                'user_id'        => $order['user_id'],
                                                'ticket_num'     => $order['ticket_num'],
                                                'money'          => $parent2_money
                                            ]; 
                                            self::insertDistributorRebate($parent2_rebate);
                                        }    

                                }
                                  
                        }
                } 
            /*** 供应商**/
            $store_money = $order['order_amount']-$rebate_money;
      
            if ($store_money > 0) {
                $store_rebate = [
                    'order_id'   => $order['id'],
                    'store_id'   => $order['store_id'],
                    'self_goods' => 1,
                    'user_id'    => $order['user_id'],
                    'ticket_num' => $order['ticket_num'],
                    'money'      => $store_money
                ];
                self::insertStoreRebate($store_rebate);
            }

                   
    }


        
}


    /**
     * [createStoreRebate 创建返利  商家购买]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    [type]      $order_id [description]
     * @return   [type]                [description]
     */
    public static function createStoreRebate($order_id)
    {
        $order = Db::name('order')->find($order_id);
        //购买用户为商家
        if ($order['buy_role'] == 1) {
           if ($order['goods_source'] == 'p') {
               /*** 平台商品**/
               
               //上传供应商
               $goods = Db::name('goods')->field('platform_markup_price')->find($order['goods_id']);
               $sales = Db::name('sales')->field('costPrice')->find($order['sales_id']);
               $store_money1 = ($sales['costPrice']+$goods['platform_markup_price'])*$order['ticket_num'];
               self::insertStoreRebate($order['id'],$order['store_id'],1,$order['user_id'],$order['ticket_num'],$store_money1);


           return TRUE;
         }

        }else{
           return FASLE;  
        }


    }




    /**
     * [insertDistributorRebate 插入分销商返利]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     */
    public static function insertDistributorRebate($data)
    {
            
            $rebate['store_id']       =  $data['store_id'];
            $rebate['order_id']       =  $data['order_id'];
            $rebate['distributor_id'] =  $data['distributor_id'];
            $rebate['is_partner']     =  $data['is_partner'];
            $rebate['buy_role']       =  $data['buy_role'];
            $rebate['user_id']        =  $data['user_id'];
            $rebate['buy_num']        =  $data['ticket_num'];
            $rebate['rebate_amount']  =  $data['money'];
            $rebate['create_time']    =  date("Y-m-d H:i:s");
            Db::name('distributor_rebate')->insert($rebate);

            return TRUE;

    } 


    /**
     * [insertStoreRebate 插入商家返利]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     */
    public static function insertStoreRebate($data)
    {

            $rebate_data['order_id']      = $data['order_id'];
            $rebate_data['store_id']      = $data['store_id'];
            $rebate_data['self_goods']    = $data['self_goods'];
            $rebate_data['user_id']       = $data['user_id'];
            $rebate_data['buy_num']       = $data['ticket_num'];
            $rebate_data['rebate_amount'] = $data['money'];
            $rebate_data['create_time']   = date("Y-m-d H:i:s");
            Db::name('store_rebate')->insert($rebate_data);

            return TRUE;

    }


    /**
     * [executeRebate 进行返利]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    [type]      $order_id [description]
     * @param    [type]      $consum   [description]
     * @return   [type]                [description]
     */
    public static function executeRebate($order_id,$consum,$send=1)
    {   
            /*** 分销商返利**/
            $distributor_rebate = Db::name('distributor_rebate')->where('order_id',$order_id)->select();
            if ($distributor_rebate) {
                foreach ($distributor_rebate as $k => $vo) {
                    $distributor_money = ($vo['rebate_amount']/$vo['buy_num'])*$consum;
                    
                    //改变分销商返利购买数量 返利金额
                    Db::name('distributor_rebate')->where('id', $vo['id'])->setDec('buy_num', $consum);
                    Db::name('distributor_rebate')->where('id', $vo['id'])->setDec('rebate_amount',$distributor_money);
                    //增加分销商返利
                    // Db::name('user')->where('id', $vo['distributor_id'])->setInc('rebate', $distributor_money);
                    Db::name('distributor')->where('user_id', $vo['distributor_id'])->setInc('rebate_total', $distributor_money);
                    //返利记录
                    $distributor  = User::get($vo['distributor_id']);
                    $distributor->money($distributor_money,$vo['distributor_id'],$type = 3,'返利',$order_id,2,$consum);
                    //返利完成删除
                    Db::name('distributor_rebate')->where(['order_id'=>$order_id,'buy_num'=>0,'rebate_amount'=>0])->delete();
                }
                if (!Db::name('distributor_rebate')->where('order_id',$order_id)->find()){
                    $order = Db::name('order')->find($order_id);
                      if ($order['buy_role'] == 3) {
                         Db::name('distributor')->where(['user_id' =>$order['sell_id']])->setInc('sell_order',1);
                      }elseif ($order['buy_role'] == 2) {
                         Db::name('distributor')->where(['user_id' =>$order['sell_id']])->setInc('buy_order',1);
                      }
                         Db::name('distributor')->where(['user_id' =>$order['sell_id']])->setInc('order_total',1);
                    if ($send == 1) {
                        //公众号推送
                        self::sendNotice($order['user_id'],$order_id); 
                    }     
 
                }

            }

            /*** 商家返利**/
           $store_rebate = Db::name('store_rebate')->where('order_id',$order_id)->select();
           if ($store_rebate) {
               foreach ($store_rebate as $k => $vo) {
                    $store_money = ($vo['rebate_amount']/$vo['buy_num'])*$consum;
                    //改变商家返利购买数量 返利金额
                    Db::name('store_rebate')->where('id', $vo['id'])->setDec('buy_num', $consum);
                    Db::name('store_rebate')->where('id', $vo['id'])->setDec('rebate_amount',$store_money);
                    
                    //增加商家返利 余额
                    $store  = Store::get($vo['store_id']);
                    $store->money($store_money,$vo['store_id'],$type = 1 ,'产品销售',$order_id);
                    
                    //返利完成删除
                    Db::name('store_rebate')->where(['order_id'=>$order_id,'buy_num'=>0,'rebate_amount'=>0])->delete();
                    
               }
                
            } 
            
            return TRUE;
    }





    /**
     * [updateRebate 修改返利  部分退款]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    [type]      $order_id [description]
     * @param    [type]      $num      [description]
     * @return   [type]                [description]
     */
    public static function updateRebate($order_id,$num)
    { 

            /*** 分销商返利**/
            $distributor_rebate = Db::name('distributor_rebate')->where('order_id',$order_id)->select();
            if ($distributor_rebate) {
                foreach ($distributor_rebate as $k => $vo) {
                    //改变分销商返利购买数量 返利金额
                    $distributor_money = ($vo['rebate_amount']/$vo['buy_num'])*$num;
                    Db::name('distributor_rebate')->where('id', $vo['id'])->setDec('rebate_amount',$distributor_money); 
                    Db::name('distributor_rebate')->where('id', $vo['id'])->setDec('buy_num', $num);

                }
                
                //完成删除
               Db::name('distributor_rebate')->where(['order_id'=>$order_id,'buy_num'=>0,'rebate_amount'=>0])->delete();
            }

           /*** 商家返利**/
           $store_rebate = Db::name('store_rebate')->where('order_id',$order_id)->select();
           if ($store_rebate) {
                foreach ($store_rebate as $k => $vo) {
                    //改变商家返利购买数量 返利金额
                    $store_money = ($vo['rebate_amount']/$vo['buy_num'])*$num;
                    Db::name('store_rebate')->where('id', $vo['id'])->setDec('rebate_amount',$store_money);
                    Db::name('store_rebate')->where('id', $vo['id'])->setDec('buy_num', $num);

                }
            }

           return TRUE; 
    }


    /**
     * [deleteRebate 删除指定的订单返利]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-31
     * @param    [type]      $order_id [description]
     * @return   [type]                [description]
     */
    public static function deleteRebate($order_id)
    {
        //删除分销商订单返利
        Db::name('distributor_rebate')->where(['order_id' => $order_id])->delete();

        //删除商家订单返利
        Db::name('store_rebate')->where(['order_id' => $order_id])->delete();         

        return TRUE;
    }


    /**
     * [sendNotice 发送模板消息]
     * @Author   ZhouYunpeng
     * @DateTime 2021-03-17
     * @return   [type]      [description]
     */
    public static function sendNotice($user_id,$order_id)
    {  
        $userModel = new User();
        $user = $userModel->get(['id'=>$user_id]);
        if ($user['openid']) {
             $app = new Application(ConfigService::load());   
              //发送模板消息
             $app->notice->send([
                                  'touser' => $user['openid'],
                                  'template_id' => 'dwRNk2sKoUfci0sOC6WHUzyF4OEUBauE8czpaXmK9tw',
                                  'miniprogram'=>['appid'=>'wxab379d255ecd6df9',
                                                  'pagepath'=>'pages/order/OrderList?state=2'
                                                 ],
                                  'data' => [
                                      'first'    => ['订单核销成功！请及时评价','#52627C'],
                                      'keyword1' => [$order_id,'#DB9728'],
                                      'keyword2' => ['已核销','#52627C'],
                                      'keyword3' => [date("Y-m-d H:i:s"),'#52627C'],
                                      'remark'   => ['感谢您的支持,如有疑问请致电易行旅行客服：0531-85333222。','#52627C'],
                                  ],
                              ]);
                }
    }


}
